<?php
/**
 * Build a JSON string.
 *
 * PHP versions 5
 *
 * Copyright (C)
 * This program is free software. You can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation. Either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program. Ff not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * @author Bastian Schröder <bs@chemanet.de>
 * @version 2008-04-10
 * @package ajaxBridge
 */

class ajaxBridge {

	/**
	 * Error level
	 *
	 * @var error_level
	 */
	public $error_level = 3;

	/**
	 * An array of Exception objects stored by register_exception method.
	 *
	 * @var exceptions
	 */
	protected $exceptions = array();

	/**
	 * Datastore for JSON output.
	 *
	 * @var json_array
	 */
	protected $json_array = array();


	/**
	 * Append an array or an value to json_array datastore. First parameter request an array or a key. In case that
	 * $pMixed is a kex the secend parameter is the value for this key.
	 *
	 * @param midex $pMixed a key or a array of keys=>values
	 * @param string $pValue (optional)
	 */
	public function append ( $pMixed, $pValue = null ) {
		if( is_array($pMixed) ){
			foreach( $pMixed as $key=>$value )
				$this->json_array[ $key ] = $value;
		}
		else
			$this->json_array[ $pMixed ] = $pValue;
	}


	/**
	 * Return the type of this response object. Can be ajax_response or ajax_error_response.
	 *
	 * @return string
	 */
	public function get_type () {
		foreach( $this->exceptions as $key=>$t1 )
			if( $key >= $this->error_level ) return 'ajax_error_response';

		return 'ajax_response';
	}


	/**
	 * Register a Exception to this object.
	 *
	 * @param Exception $pException
	 * @param int $plevel (optional)
	 */
	public function register_exception ( $pException, $pLevel = 1 ) {
		$this->exceptions[ $pLevel ][] = $pException;
	}


	/**
	 * Return a json encoded string.
	 *
	 * @return string
	 */
	public function json_encode () {
		$return_array = array( "type"=>$this->get_type() );

		// exceptions
		if( count( $this->exceptions ) > 0 ){
			$exceptions = array();
			foreach( $this->exceptions as $level )
				foreach( $level as $e ) $exceptions[] = $e->getMessage();
			$return_array[ 'exceptions' ] = $exceptions;
		}

		// datastore
		foreach( $this->json_array as $key=>$value ){
			$return_array[ $key ] = $value;
		}

		return json_encode( $return_array );
	}

} // End of ajaxBridge

?>